package cz.proks.bank.manager;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cz.proks.bank.BankConstants;
import cz.proks.bank.dao.BankDao;
import cz.proks.bank.domain.Bank;
import cz.proks.bank.manager.exeception.BankRegisterException;

@Service
public class BankManager {
	private final Logger log = Logger.getLogger(getClass());
	
	@Autowired
	private BankDao bankDao;
	
	@Autowired
	private ClearingManager clearingManager;
	
	private Bank bank;
	
	public void registerBank(String bankCode, String bankName) throws BankRegisterException {
		log.debug("registerBank():: Start with bank code '" + bankCode + "'");
		
		Bank bank = bankDao.getByCode(bankCode);
		
		if (bank == null) {
			String bankKey = clearingManager.registerBank(bankCode);
			
			bank = new Bank();
			
			bank.setId(bankKey);
			bank.setCode(bankCode);			
			bank.setName(bankName);
			
			bankDao.create(bank);			
		}
		
		log.debug("registerBank():: Exit with bank '" + bank + "'");
	}
	
	public Bank getBank() {
		if (bank == null) {
			List<Bank> banks = bankDao.listAll();
			bank = banks != null && !banks.isEmpty() ? banks.get(0) : null; 
		}
		
		return bank; 
	}
	
	public Bank getBankByCode(String bankCode) {
		return bankDao.getByCode(bankCode);
	}
	
	public boolean isLocalBank(String bankCode) {
		return BankConstants.BANK_CODE.equals(bankCode);
	}
		
}
